package org.jeecg.modules.mr.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.config.mybatis.TenantContext;
import org.jeecg.modules.mr.entity.MrBookMeters;
import org.jeecg.modules.mr.service.IMrBookMetersService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

 /**
 * @Description: 抄表顺序
 * @Author: jeecg-boot
 * @Date:   2022-02-03
 * @Version: V1.0
 */
@Api(tags="抄表顺序")
@RestController
@RequestMapping("/mr/mrBookMeters")
@Slf4j
public class MrBookMetersController extends JeecgController<MrBookMeters, IMrBookMetersService> {
	@Autowired
	private IMrBookMetersService mrBookMetersService;

	/**
	 * 分页列表查询
	 *
	 * @param mrBookMeters
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "抄表顺序-分页列表查询")
	@ApiOperation(value="抄表顺序-分页列表查询", notes="抄表顺序-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(MrBookMeters mrBookMeters,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<MrBookMeters> queryWrapper = QueryGenerator.initQueryWrapper(mrBookMeters, req.getParameterMap());
		Page<MrBookMeters> page = new Page<MrBookMeters>(pageNo, pageSize);
		IPage<MrBookMeters> pageList = mrBookMetersService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param mrBookMeters
	 * @return
	 */
	@AutoLog(value = "抄表顺序-添加")
	@ApiOperation(value="抄表顺序-添加", notes="抄表顺序-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody MrBookMeters mrBookMeters) {
		if(oConvertUtils.isNotEmpty(mrBookMeters.getCustomerId())){

			int count = mrBookMetersService.count(new LambdaQueryWrapper<MrBookMeters>()
					.in(MrBookMeters::getCustomerId, mrBookMeters.getCustomerId().split(","))
					//.eq(MrBookMeters::getBookId,mrBookMeters.getBookId())
					.eq(MrBookMeters::getDelFlag,0));
			if(count>0){
				return Result.error("选择的水表用户已在抄表本中！");
			}

			String[] cusIds = mrBookMeters.getCustomerId().split(",");
			String[] cusNames = mrBookMeters.getCusName().split(",");
			for (int i = 0; i < cusIds.length; i++) {
				MrBookMeters meters = new MrBookMeters();
				BeanUtils.copyProperties(mrBookMeters,meters);
				meters.setCustomerId(cusIds[i]);
				meters.setCusName(cusNames[i]);
				meters.setOrderNo((null != meters.getOrderNo() ? meters.getOrderNo() : 1 )+i);
				mrBookMetersService.save(meters);
			}
			return Result.OK("添加成功！");
		}
		return Result.error("添加异常！");
	}
	/**
	 *   抄表顺序-保存
	 *
	 * @param orderData
	 * @return
	 */
	@AutoLog(value = "抄表顺序-保存")
	@ApiOperation(value="抄表顺序-保存", notes="抄表顺序-保存")
	@PostMapping(value = "/bookOrderMater")
	public Result<?> bookOrderMater(@RequestBody JSONArray orderData) {
		orderData= JSON.parseArray(orderData.toJSONString());
		mrBookMetersService.saveOrderMater(orderData);
		return Result.OK("重新排序成功！");
	}

	/**
	 *  编辑
	 *
	 * @param mrBookMeters
	 * @return
	 */
	@AutoLog(value = "抄表顺序-编辑")
	@ApiOperation(value="抄表顺序-编辑", notes="抄表顺序-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody MrBookMeters mrBookMeters) {
		if(oConvertUtils.isNotEmpty(mrBookMeters.getCustomerId())){
			String[] cusIds = mrBookMeters.getCustomerId().split(",");
			String[] cusNames = mrBookMeters.getCusName().split(",");

			boolean remove = mrBookMetersService.remove(new LambdaQueryWrapper<MrBookMeters>()
					.in(MrBookMeters::getCustomerId, cusIds)
					//.eq(MrBookMeters::getBookId, mrBookMeters.getBookId())
					.eq(MrBookMeters::getDelFlag, 0));
			//先删除 再增加

			for (int i = 0; i < cusIds.length; i++) {
				MrBookMeters meters = new MrBookMeters();
				BeanUtils.copyProperties(mrBookMeters,meters);
				meters.setCustomerId(cusIds[i]);
				meters.setCusName(cusNames[i]);
				meters.setOrderNo(meters.getOrderNo()+i);
				mrBookMetersService.save(meters);
			}
		}
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "抄表顺序-通过id删除")
	@ApiOperation(value="抄表顺序-通过id删除", notes="抄表顺序-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		mrBookMetersService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "抄表顺序-批量删除")
	@ApiOperation(value="抄表顺序-批量删除", notes="抄表顺序-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.mrBookMetersService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "抄表顺序-通过id查询")
	@ApiOperation(value="抄表顺序-通过id查询", notes="抄表顺序-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		MrBookMeters mrBookMeters = mrBookMetersService.getById(id);
		if(mrBookMeters==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(mrBookMeters);
	}

	/**
	 * 查询抄表本抄表用户记录
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "查询抄表本抄表用户记录")
	@ApiOperation(value="查询抄表本抄表用户记录", notes="查询抄表本抄表用户记录")
	@GetMapping(value = "/queryBookMaterById")
	public Result<?> queryBookMaterById(@RequestParam(name="id",required=true) String id,String key) {
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		if (oConvertUtils.isEmpty(TenantContext.getTenant())) {
			TenantContext.setTenant(sysUser.getRelTenantIds());
		}
		List<Map<String, Object>> mapList = mrBookMetersService.queryBookReadMater(id,key);
		if(mapList==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(mapList);
	}
	/**
	 * 查询抄表本水表顺序
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "查询抄表本水表顺序")
	@ApiOperation(value="查询抄表本水表顺序", notes="查询抄表本水表顺序")
	@GetMapping(value = "/queryBookMaterOrder")
	public Result<?> queryBookMaterOrder(@RequestParam(name="id",required=true) String id) {
		List<Map<String, Object>> mapList = mrBookMetersService.queryBookOrderMater(id);
		if(mapList==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(mapList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param mrBookMeters
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, MrBookMeters mrBookMeters) {
        return super.exportXls(request, mrBookMeters, MrBookMeters.class, "抄表顺序");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, MrBookMeters.class);
    }

}
